<template>
  <div class="box-yuyi">
    <div class="box-left" v-loading="treeLoading">
      <avue-tree :option="treeOption"
                 :data="treeData"
                 ref="tree"
                 @update="handleTreeUpdate"
                 @save="handleTreeSave"
                 @node-click="nodeClick">
        <div class="custom-tree-node show-hide" slot-scope="{ node, data }">
          <span class="text" onselectstart="return false" :title="data.checkItem">
            <i :class="data.icon"/> {{ data.checkItem }}
          </span>
          <span class="tree-btn" >
            <!--<el-button
              type="text"
              size="small"
              class="btn"
              v-if="data.pid === '0'"
              @click.stop="handleAddRowTree(data)">
              <i class="el-icon-plus"></i>
            </el-button>-->
            <el-button
              type="text"
              size="small"
              class="btn"
              v-if="data.pid !== '0'"
              @click.stop="handleShowRowEdit(data)">
              <i class="el-icon-edit"></i>
            </el-button>
            <el-button
              type="text"
              size="small"
              class="btn"
              v-if="data.pid !== '0'"
              @click.stop="() => removeNode(data.id)">
              <i style="color: #F56C6C" class="el-icon-delete"></i>
            </el-button>
          </span>
        </div>
      </avue-tree>
    </div>
    <div class="box-content">

      <el-tabs type="border-card" @tab-click="handleTabClick">
        <el-tab-pane v-for="(item, index) in tabList"
                     :key="index"
                     :label="item.label">

          <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="检测项：">
              <el-input size="small" v-model="searchData.val" clearable></el-input>
            </el-form-item>
            <el-form-item class="search-btn">
              <el-button type="primary" size="small" icon="el-icon-search" @click="onSubmit">查询</el-button>
              <el-button type="primary" size="small" icon="el-icon-search" @click="handleAdd">添加</el-button>
            </el-form-item>
          </el-form>

          <div class="list">
            <div class="list-box" v-loading="listLoading">

              <test-item-list v-for="(item, index) in listData"
                              :key="index"
                              :item="item"
                              @handleSwitch="getList"
                              @handleDelSuccess="getList"
                              @handleEdit="handleEdit(item, index)"
                              class="test-item">
              </test-item-list>

              <div class="empty" v-if="Number(page.total)<1">
                暂无数据
              </div>

            </div>
          </div>

          <el-pagination
            class="page"
            background
            v-if="Number(page.total)>0"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page.pageNo"
            :page-sizes="[20, 40, 60, 80]"
            :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="Number(page.total)">
          </el-pagination>

        </el-tab-pane>
      </el-tabs>

      <el-dialog :title="dialogTitle"
                 width="70%"
                 top="5vh"
                 :destroy-on-close="true"
                 :close-on-click-modal="false"
                 :close-on-press-escape="false"
                 :visible.sync="dialogAddEdit"
                 :before-close="handleBeforeClose">
        <test-item-add :cascaderList="treeData"
                       :cascaderDisabled="cascaderDisabled"
                       :loading="loading"
                       :obj="rowData"
                       :type="type"
                       @handleSubmit="handleSubmit"></test-item-add>
      </el-dialog>

    </div>

  </div>
</template>

<script>
import {
  addTestItemList, addTreeTestItem, delTreeTestItem,
  editTestItemList, editTreeTestItem,
  getTestItemList,
  getTreeTestItem
} from '../../../../api/testItem/testItemBasics'
import TestItemList from '../settingComponents/testItem/testItemList'
import { mapActions } from 'vuex'
import TestItemAdd from '../settingComponents/testItem/testItemAdd'
import { getSysDicId } from '../../../../api/dictionary/dictionary'

export default {
  name: 'TestItemManage',
  components: {
    TestItemAdd,
    TestItemList
  },
  // 检测项管理
  data () {
    return {
      treeLoading: true,
      treeData: [],
      tabList: [],
      title: '新建检测项',
      dialogTitle: '添加检查项',
      dialogAddEdit: false,
      loading: false,
      rowData: {},
      type: 'add',
      listData: [],
      tabsMenuCode: '',
      page: {
        pageSize: 20,
        pageNo: 1,
        total: 0
      },
      leftData: '',
      listLoading: false,
      searchData: {
        val: ''
      },
      params: [],
      cascaderDisabled: false
    }
  },
  mounted () {
    this.setNavNarrow(true)
    this.getTree()
    this.getTabsMenu()
  },
  computed: {
    treeOption () {
      return {
        title: this.title,
        // addBtn: false,
        menu: false,
        defaultExpandAll: true,
        // accordion: true, // 只展开一层
        formOption: {
          labelWidth: 100,
          column: [{
            label: '所属类别',
            prop: 'checkType',
            type: 'select',
            dicUrl: '/yuyi-config-boot/api/config/dictData/child?dictTypeName=sx_check_type',
            props: {
              label: 'dictLabel',
              value: 'dictValue'
            },
            span: 24,
            row: true,
            rules: [
              {
                required: true,
                message: '请选择所属类别',
                trigger: 'change'
              }
            ]
          }, {
            label: '检测项编码',
            prop: 'checkCode',
            span: 24,
            row: true,
            rules: [
              {
                required: true,
                message: '请输入检测项编码',
                trigger: 'blur'
              }
            ]
          }, {
            label: '检测项',
            prop: 'checkItem',
            span: 24,
            row: true,
            rules: [
              {
                required: true,
                message: '请输入检测项',
                trigger: 'blur'
              }
            ]
          }, {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            span: 24,
            row: true
          }]
        },
        props: {
          labelText: '标题',
          label: 'checkItem',
          value: 'id',
          children: 'children'
        }
      }
    }
  },
  methods: {
    ...mapActions('profile/navNarrow', ['setNavNarrow']),
    getTree () {
      getTreeTestItem().then(res => {
        this.treeData = res.data.data
        this.treeLoading = false
      }).catch(() => {
        this.treeLoading = false
      })
    },
    getTabsMenu () {
      getSysDicId('sx_check_link').then(res => {
        res.data.data.map(item => {
          this.tabList.push({
            label: item.dictLabel,
            value: item.dictValue
          })
        })
        this.tabsMenuCode = this.tabList[0].value
        this.getList()
      })
    },
    handleAddRowTree (data) {
      // 显示新增树
      // { checkType: data.checkType }
      this.$refs.tree.rowAdd()
      this.title = '新建检测项'
    },
    handleShowRowEdit (data) {
      // 显示修改树
      this.title = '修改检测项'
      // 修改树节点
      this.$refs.tree.nodeContextmenu('t', data)
      this.$refs.tree.rowEdit()
    },
    handleTreeSave (node, data, done) {
      // 新增树提交
      const obj = data
      obj.checkTypeName = data.$checkType
      obj.pid = data.checkType
      addTreeTestItem(obj).then(res => {
        this.$message.success('新增成功！')
        this.getTree()
        done()
      }).catch(() => {
        done()
      })
    },
    handleTreeUpdate (node, data, done) {
      // 修改树
      console.log(node, data)
      const obj = data
      obj.checkTypeName = data.$checkType
      editTreeTestItem(data).then(res => {
        this.$message.success('修改操作成功！')
        this.getTree()
        done()
      }).catch(() => {
        done()
      })
    },
    removeNode (id) {
      // 删除树节点
      this.$confirm('该操作将永久删除该条信息，是否删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delTreeTestItem([id]).then(res => {
          this.$message.success('删除成功！')
          this.getTree()
        })
      }).catch(() => {
      })
    },
    nodeClick (data) {
      // 选择tree节点
      console.log(data)
      this.leftData = data
    },
    getList () {
      const param = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
        params: [{
          name: 'checkLink',
          op: 'eq',
          value: this.tabsMenuCode
        }]
      }
      if (this.params.length > 0) {
        param.params = param.params.concat(this.params)
      }

      this.listLoading = true
      getTestItemList(param).then(res => {
        this.listData = res.data.data.list
        this.page.total = res.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.page.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.page.pageNo = val
      this.getList()
    },
    handleTabClick (val) {
      this.page.pageNo = 1
      this.tabsMenuCode = this.tabList[val.index].value
      this.getList()
    },
    handleEdit (item, index) {
      // 修改
      this.cascaderDisabled = item.checkItem !== '' && item.checkItem !== undefined
      this.rowData = item
      this.dialogAddEdit = true
      this.dialogTitle = '修改'
      this.type = 'edit'
    },
    onSubmit () {
      if (this.searchData.val) {
        this.params = [{
          name: 'checkItem',
          op: 'like',
          value: this.searchData.val
        }]
      } else {
        this.params = []
      }
      this.getList()
    },
    handleAdd () {
      this.dialogAddEdit = true
      this.dialogTitle = '添加检查项'
      this.rowData.checkLink = this.tabsMenuCode
      this.rowData.checkItem = this.leftData.checkItem || ''
      this.rowData.standardIdentifier = this.leftData.checkCode ? (this.tabsMenuCode + '-' + this.leftData.checkCode) : this.tabsMenuCode
      this.cascaderDisabled = this.rowData.checkItem !== '' && this.rowData.checkItem !== undefined
      this.rowData.checkScope = 1
      this.rowData.isEnable = true
    },
    handleSubmit (obj) {
      // 新增修改提交
      this.loading = true
      const request = this.type === 'add' ? addTestItemList(obj) : editTestItemList(obj)
      request.then(res => {
        this.getList()
        this.$message.success(this.type === 'add' ? '新增成功！' : '修改成功！')
        this.loading = false
        this.dialogAddEdit = false
        this.rowData = {}
        this.type = 'add'
      }).catch(() => {
        this.loading = false
      })
    },
    handleBeforeClose (done) {
      this.dialogAddEdit = false
      this.loading = false
      this.rowData = {}
      this.type = 'add'
      done()
    }
  }
}
</script>

<style lang="scss" scoped>
  .box-yuyi {
    .box-left {
      width: 400px;
    }

    ::v-deep .avue-tree {
      height: calc(100% - 5px);
    }

    ::v-deep .el-tree-node__content {
      width: 100%;

      .show-hide {
        .text {
          display: inline-block;
          max-width: 260px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          vertical-align: middle;
        }
      }

      &:hover {
        .tree-btn {
          display: inline-block;
        }
      }
    }

    .tree-btn {
      margin-left: 20px;
      vertical-align: middle;
      display: none;
      .btn{
        font-size: 16px;
        &.btn {
          margin-left: 8px;
        }
      }

      .btn:hover {
        opacity: 0.8;
      }
    }

    .box-content {
      width: calc(100% - 415px);
      padding: 0;
    }

    ::v-deep .el-form-item {
      margin-bottom: 10px
    }

    ::v-deep .el-tabs__content {
      height: calc(100vh - 125px);

      .el-tab-pane {
        height: 100%;
      }

      .list {
        height: calc(100vh - 240px);
        margin: 0 -15px -15px -15px;
        padding: 0 12px 20px;
        overflow-y: auto;
      }

      .list-box {
        display: flex;
        justify-content: flex-start;
        flex-wrap: wrap;

        .test-item {
          margin-bottom: 20px;
          margin-right: 15px;
          width: 300px;
          max-width: calc(50% - 15px);
        }
      }

      .page {
        margin-top: 20px;
        text-align: right;
      }

      .empty {
        padding: 30px;
        text-align: center;
        margin: 0 auto;
      }
    }
  }
</style>
